package com.example.udpLearn.udp4;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * 客户端多次发送数据，服务端接收数据，并返回数据给客户端：客户端
 */
public class Client {
    public static void main(String[] args) throws IOException {

        System.out.println("客户端启动...");

        DatagramSocket socket = new DatagramSocket(7777);

        Scanner scanner = new Scanner(System.in);
        while (true) {
            String string = scanner.nextLine();
            if ("exit".equals(string)) {
                System.out.println("客户端退出...");
                socket.close();
                break;
            }
            byte[] bytes = string.getBytes();
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);
            socket.send(packet);

            /**
             * 接收服务端发来的数据
             */
            byte[] clientReceiveData = new byte[1024 * 64];
            DatagramPacket packetClient = new DatagramPacket(clientReceiveData, clientReceiveData.length);
            socket.receive(packetClient);
            System.out.println("服务端发来的数据：" + new String(packetClient.getData(), 0, packetClient.getLength()));
            System.out.println("服务端发来的数据来自IP：" + packetClient.getAddress().getHostAddress());
            System.out.println("服务端发来的数据来自Port" + packetClient.getPort());
            System.out.println("===========================================");
        }


    }
}
